package cn.codeforfun.controller;

import cn.codeforfun.common.model.User;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.CaptchaRender;
import org.apache.log4j.Logger;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

/**
 * Created by Administrator on 2016/3/18.
 */
public class IndexController extends Controller {
    private final Logger log = Logger.getLogger(IndexController.class);

    public void index() {
        renderJsp("index.jsp");
    }

    public void loginPage() {
        renderJsp("/common/login.jsp");
    }

    public void registPage() {
        renderJsp("/common/regist.jsp");
    }

    public void img() {
        CaptchaRender captchaRender = new CaptchaRender();
        render(captchaRender);
    }

    @Clear
    public void login() {
        boolean codeVali = CaptchaRender.validate(this, getPara("randomCode"));
        if (codeVali) {
            User user = User.dao.findByUsername(getPara("username"));
            if (user == null) {
                setAttr("result", "用户名错误");
                renderJson();
            } else {
                String password = getPara("password");
                String salt = user.getSalt();
                String md5Pwd = new SimpleHash("md5", password, salt, 2).toHex();
                if (!user.getPassword().equals(md5Pwd)) {
                    setAttr("result", "密码错误");
                    renderJson();
                } else {
                    getSession().setAttribute("user", user);
                    setAttr("result", "success");
                    renderJson();
                }
            }
        } else {
            setAttr("result", "验证码输入错误");
            renderJson();
        }
    }

    public void logout() {
        getSession().removeAttribute("user");
        setAttr("result", "success");
        renderJson();
    }

    @Before(Tx.class)
    public void regist() {
        User user = User.dao.findByUsername(getPara("username"));
        if (user == null) {
            String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
            String password = new SimpleHash("md5", getPara("password"), salt, 2).toHex();
            new User().set("username", getPara("username")).set("name", getPara("username")).set("password", password).set("salt", salt).save();
            setAttr("result", "success");
            renderJson();
        } else {
            setAttr("result", "用户名已存在");
            renderJson();
        }
    }
}
